#include "xaudio.h"

#include <QMutex>
#include <iostream>

struct XTime {
    XTime(int tms) {
        h = (tms / 1000) / 3600;
        m = ((tms / 1000) % 3600) / 60;
        s = (tms / 1000) % (3600 * 60);
        ms = tms % 1000;
    }
    std::string ToString() {
        char buf[16] = {0};
        sprintf(buf, "%d:%d:%d.%d", h, m, s, ms);
        return buf;
    }
    int h = 0;
    int m = 0;
    int s = 0;
    int ms = 0;
};

class CXAudio : public XAudio {

public:
    QMutex mutex;

    CXAudio(){}
    bool exportAudio(std::string src, std::string out, int beginMs, int outMs){
        //ffmpeg -i 原音频.mp4 -ss 时：分：秒：毫秒 -t 时：分：秒：毫秒 -vn -y 音乐.mp3
        std::string cmd = "ffmpeg";
        cmd += " -i ";
        cmd += src;
        cmd += " ";
        if (beginMs > 0) {
            cmd += " -ss ";
            XTime xt(beginMs);
            cmd += xt.ToString();
        }

        if (outMs > 0) {
            cmd += " -t ";
            XTime xt(outMs);
            cmd += xt.ToString();
        }
        cmd += " -vn -y ";
        cmd += out;
        //std::cout << cmd << std::endl;
        mutex.lock();
        system(cmd.c_str());
        mutex.unlock();
        return true;
    }

    bool mergeAudio(std::string v, std::string a, std::string out){
        //ffmpeg -i 无音频.mp4 -i 音乐.mp3 - c copy 有音频.mp4
        std::string cmd = "ffmpeg -i ";
        cmd += v;
        cmd += " -i ";
        cmd += a;
        cmd += " -c copy ";
        cmd += out;
        mutex.lock();
        system(cmd.c_str());
        mutex.unlock();
        return true;
    }

};

XAudio *XAudio::getInstance()
{
    static CXAudio ca;
    return &ca;
}

XAudio::XAudio(QObject *parent)
    : QObject{parent}
{}
